package com.lollipop.synthential.concurrency.excutorsdemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: J.K
 * @Date: 2021-04-27 15:54
 * @Description: 创建线程池:
 * 1.通过Executors工厂方法创建
 * 2.通过new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)自定义创建
 */
public class CreateExecutorDemo1 {

    public static void main(String[] args) {

        // 通过Executors工厂方法创建线程池
        // 创建使用单个线程的线程池
        ExecutorService executorService1 = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            executorService1.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "正在执行任务……");
            });
        }

        // 创建使用固定线程数的线程池
        ExecutorService executorService2 = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            executorService2.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "正在执行任务...");
            });
        }

        // 创建一个会根据需要创建新线程的线程池
        ExecutorService executorService3 = Executors.newCachedThreadPool();
        executorService3.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "正在执行任务...");
        });

        // 创建拥有固定线程数量的定时线程任务的线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        System.out.println("时间：" + System.currentTimeMillis());
        for (int i = 0; i < 6; i++) {
            scheduledExecutorService.schedule(() -> {
                System.out.println("时间：" + System.currentTimeMillis() + "--" + Thread.currentThread().getName() + "正在执行任务...");
            }, 3, TimeUnit.SECONDS);
        }

        // 创建只有一个线程的定时线程任务的线程池
        ScheduledExecutorService scheduledSingleExecutorService = Executors.newSingleThreadScheduledExecutor();
        System.out.println("时间：" + System.currentTimeMillis());
        for (int i = 0; i < 5; i++) {
            scheduledSingleExecutorService.schedule(() -> {
                System.out.println("时间：" + System.currentTimeMillis() + "--" + Thread.currentThread().getName() + "正在执行任务");
            }, 3, TimeUnit.SECONDS);
        }
    }
}
